/*
 * @Author: zeki mini
 * @Date: 2021-01-04 16:50:17
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-15 15:52:35
 * @Description: 更换手机输入新手机号
 */
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, TextInput, NativeModules, SafeAreaView } from 'react-native';
import { msg, XMHeader, BackImageOn, Button, ValidConst, cache, AsyncStorage } from '@/common';
import { isAndroid, px2dp, fontColorLightGray, fontColorCoffee, screenWidth } from '@/styles';
import api from '@/api';

const { Submit } = Button;
const userApi = api.user;
export default class ChangePhoneNew extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonDisable: true,
      newNumber: '',
      serviceNumber: '',
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.SERVICE_NUMBER).then((res) => {
      this.setState({ serviceNumber: res });
    });
  }

    basicRegex = (callback) => {
      const { newNumber } = this.state;
      const regex = ValidConst.phone;
      if (newNumber === '') {
        NativeModules.WindowModule.showWindow({
          content: '请输入手机号',
          onlyRightBtn: '1'
        }, (e) => { });
        return;
      }
      if (!regex.test(newNumber)) {
        NativeModules.WindowModule.showWindow({
          content: '请输入正确的手机号码',
          onlyRightBtn: '1'
        }, (e) => { });
        return;
      }
      callback && callback(newNumber);
    }

    buttonClickActioin = (user) => {
      const { serviceNumber } = this.state;
      this.basicRegex((mobile) => {
        if (mobile === user.wholeMobile) {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '温馨提醒',
            text: '与当前绑定手机号相同',
            okText: '确定',
          });
          return;
        }
        // 手机号查重
        userApi.changePhoneCheckPhone({ mobile: mobile }).then(res => {
          // 0 正常新号  1 已绑定其他账户未实名 2 绑定账户并实名
          if (res.success) {
            if (res.data === 0) {
              msg.emit('router: goToNext', {
                routeName: 'ChangePhone',
                user: user,
                newPhoneNumber: mobile,
              });
            } else if (res.data === 1) {
              msg.emit('app:messageBox', {
                isVisible: true,
                text: <Text>
                  <Text style={{ color: fontColorCoffee }}>{mobile}</Text>
                  号码已绑定其他用户，是否要继续换绑？
                </Text>,
                okText: '换绑',
                cancelText: '暂不处理',
                okFn: () => {
                  msg.emit('router: goToNext', {
                    routeName: 'ChangePhone',
                    user: user,
                    newPhoneNumber: mobile,
                  });
                },
              });
            } else if (res.data === 2) {
              msg.emit('app:messageBox', {
                isVisible: true,
                text: <Text>
                  <Text style={{ color: fontColorCoffee }}>{mobile}</Text>
                  <Text>号码已绑定其他实名用户，如有疑问请联系客服。客服电话：</Text>
                  {' '}
                  <Text style={{ color: fontColorCoffee }}>{serviceNumber}</Text>
                </Text>,
                okText: '我知道了',
              });
            }
          } else {
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '温馨提醒',
              text: res.msg,
              okText: '确定',
            });
          }
        });
      });
    }

    render() {
      const { buttonDisable } = this.state;
      const { navigation } = this.props;
      const state = navigation.state || {};
      const params = state.params || {};
      const { user } = params;
      return (
        <SafeAreaView>

          <XMHeader
            title='更换手机号'
            renderLeft={() => {
              return <BackImageOn onClick={() => { msg.emit('router: back'); }} />;
            }}
          />
          <View>
            <Text style={styles.titleStyle}>输入新手机号</Text>
            <View style={styles.desViewStyle}>
              <Text style={styles.desxribleStyle}>
                换绑手机号后，下次登录需使用新绑定的手机号进行登录。
                <Text style={styles.phoneStyle}>
                  当前手机号：
                  {user.mobile}
                </Text>
              </Text>
            </View>
          </View>
          <TextInput
            placeholderTextColor={fontColorLightGray}
            selectionColor={fontColorCoffee}
            placeholder='请输入手机号'
            maxLength={11}
            keyboardType='number-pad'
            underlineColorAndroid='transparent'
            style={styles.textInputStyle}
            onChangeText={(text) => {
              this.setState({
                newNumber: text
              });
              if (text.length >= 11) {
                this.setState({
                  buttonDisable: false
                });
              } else {
                this.setState({
                  buttonDisable: true
                });
              }
            }}
          />
          <Submit
            text='下一步'
            boxStyle={styles.bottomBtn}
            disabled={buttonDisable}
            onClick={() => {
              this.buttonClickActioin(user);
            }}
          />
        </SafeAreaView>
      );
    }

    callServicePhone = () => {
      const { serviceNumber } = this.state;
      if (serviceNumber.length <= 0) return;
      const url = `tel:${serviceNumber}`;
      Linking.canOpenURL(url)
        .then((supported) => {
          if (!supported) {
            NativeModules.WindowModule.showWindow(
              {
                content: `您的设备不支持该功能，请手动拨打${phone}`,
                onlyRightBtn: '1',
              },
              (e) => {
              },
            );
            return;
          }
          return Linking.openURL(url);
        })
        .catch((err) => {
          msg.emit('app:tip', { text: err });
        });
    };
}
const styles = StyleSheet.create({
  titleStyle: {
    marginLeft: px2dp(32 * 2),
    marginRight: px2dp(32 * 2),
    marginTop: px2dp(40 * 2),
    fontSize: px2dp(24 * 2),
    color: '#333232',
    fontWeight: '500'
  },
  desViewStyle: {
    marginLeft: px2dp(32 * 2),
    marginRight: px2dp(32 * 2),
    marginTop: px2dp(40 * 2),
    flexDirection: 'row',
  },
  desxribleStyle: {
    fontSize: px2dp(14 * 2),
    color: '#9D9A95',
  },
  phoneStyle: {
    fontSize: px2dp(14 * 2),
    color: '#333232',
  },
  bottomBtn: {
    marginLeft: px2dp(28 * 2),
    marginTop: px2dp(40 * 2),
    width: screenWidth - px2dp(28 * 4),
    height: px2dp(44 * 2),
    borderRadius: px2dp(44)
  },
  buttonFalse: {
    backgroundColor: '#BA914A'
  },
  bottonTrue: {
    backgroundColor: '#BA914A'
  },
  textInputStyle: {
    fontSize: px2dp(32),
    padding: 0,
    marginTop: px2dp(32 * 2),
    marginLeft: px2dp(32 * 2),
    marginRight: px2dp(32 * 2),
    height: px2dp(44 * 2),
    borderBottomWidth: px2dp(0.4),
    borderBottomColor: '#F0EFEF',
  },
});
